import Taro, {Component, Config} from '@tarojs/taro'
import { Button, Image, View, Text } from '@tarojs/components'
import './index.scss'
import Calc from '@/utils/calc'
import lodash from '@/utils/lodash'
import { skuById, getPage } from '@/api/productApi'
import {verifyUserLogin, setGlobalData} from "@/utils/storage"
import { toCalcOrderPage, toHomePage, toUserLoginPage, toGoodsPage } from '@/utils/page_router'
import { getCartPage, delBatchCart, updateCart, getCartInfo, updateCartNumber } from '@/api/userApi'
import { headImg, formatAmount, getThumbnailConfig } from '@/utils/utils'
import { TitleOne, Loading, GoodsOneList, GoodsOneItem, GoodsNumber, TabBar, GoodsSelect } from '@/components/index'
import { APP_SYSTEM_INFO } from "@/config/config"
// import {APP_TABBAR_HEIGHT} from "@/config/config"

//  过滤购物车信息
const filterCartInfo = i => {
  const p = i.productInfo
  const s = p.skuInfo
  const goods = {
    id: i.id,
    name: p.name,
    isSku: p.isSku,
    images: p.images,
    number: i.number,
    productId: p.id,
  }
  if (p.isSku) {
    Object.assign(goods, {
      skuId: s.id,
      specSnap: s.specSnap,
      salePrice: s.salePrice,
    })
  } else {
    Object.assign(goods, {
      salePrice: p.salePrice
    })
  }
  return goods
}

//  是否可提交
const isSubmit = ({ checkList }) => {
  return checkList.length > 0
}

// const tabBarHeight = APP_TABBAR_HEIGHT()
// const tabBarHeight = getGlobalData('tabBarHeight')

export default class Index extends Component {
  state: any
  config: Config = {
    backgroundColor: process.env.backgroundColor,
    backgroundTextStyle: "dark",
    enablePullDownRefresh: true,
    navigationBarTitleText: '购物车',
    navigationBarTextStyle: process.env.navigationBarTextStyle,
    navigationBarBackgroundColor: process.env.backgroundColor
  }

  constructor() {
    super(...arguments)
    this.state = {
      page: 1,
      loading: true,
      isLogin: false,
      cartList: [],
      checkList: [],
      goodsList: [],
      goodsInfo: {},
      showSelect: false,
      cartStatus: true,
      totalAmount: 0,
    }
  }

  componentWillMount() {
    this.getUserLikePage()
  }

  componentDidShow() {
    this.setState({
      page: 1
    }, () => {
      this.getShoppingCart()
    })
    verifyUserLogin({
      success: () => {
        this.setState({
          isLogin: true
        })
      },
      fail: () => {
        this.setState({
          isLogin: false
        })
      }
    })
  }

  //  下拉刷新
  onPullDownRefresh() {
    this.setState({
      page: 1
    }, () => {
      this.getShoppingCart()
    })
  }

  /**
   * 猜用户喜欢
   */
  getUserLikePage() {
    getPage({ page: 1, limit: 6 }).then(res => {
      const { list } = res.data
      this.setState({
        goodsList: list
      })
    })
  }

  /**
   * 取用户购物车
   */
  getShoppingCart() {
    const { page, cartList } = this.state
    getCartPage({ page, limit: 100 }).then(res => {
      const { list, totalCount } = res.data
      const arr = list.map(i => filterCartInfo(i))
      this.setCartCount(totalCount)
      this.setState({
        page: page+1,
        cartList: page === 1 ? arr : cartList.concat(arr)
      }, () => {
        this.setState({
          loading: false
        })
        Taro.stopPullDownRefresh()
      })
    }).catch(() => {
      this.setCartCount(0)
      this.setState({
        loading: false,
        cartList: []
      })
    })
  }

  //  选中商品事件
  onCheckGoods(_i, key) {
    const { checkList } = this.state
    const ind = checkList.indexOf(key)
    if (ind >= 0) {
      checkList.splice(ind, 1)
    } else {
      checkList.push(key)
    }

    this.setState({
      checkList
    }, () => {
      this.calcShoppingCart()
    })
  }

  //  全选
  onCheckAll() {
    const { cartList, checkList } = this.state
    const checks:any = []
    if(cartList.length !== checkList.length) {
      cartList.map((item, key) => {
        checks.push(key)
        return item
      })
    }
    this.setState({
      checkList: checks
    }, () => {
      this.calcShoppingCart()
    })
  }

  //  数量变化 change 事件
  onChangeNumber(item, key, e) {
    const { cartList } = this.state
    Taro.showLoading({ title: '请稍后', mask: true })
    updateCartNumber({ id: item.id, number: e }).then(() => {
      item.number = e
      cartList[key] = item
      this.setState({
        cartList
      }, () => {
        this.calcShoppingCart()
        Taro.hideLoading()
      })
    })
  }

  //  计算购物车
  calcShoppingCart() {
    const { cartList, checkList } = this.state
    const carts = {}
    let totalAmount = 0
    checkList.map(key => {
      const item = cartList[key]
      const total = Calc.Mul(item.salePrice, item.number)
      totalAmount = Calc.Add(totalAmount, total)
      carts[item.id] = {
        ...item,
        totalPrice: total
      }
    })
    this.setState({
      totalAmount: totalAmount
    })
  }

  //  写入购物车数量
  setCartCount(number) {
    setGlobalData({ cartCount: number })
    // updateTabBarBadge(2, number)
  }

  //  切换购物车状态
  onSwitchStatus(bool) {
    this.setState({
      cartStatus: bool
    })
  }

  //  去结算
  onSubmitCart() {
    const { cartList, checkList } = this.state
    const data = checkList.map(key => {
      const i = cartList[key]
      return { id: i.productId, skuId: i.skuId, cartId: i.id, number: i.number }
    })
    toCalcOrderPage({ cartList: data })
    this.setState({
      checkList: [],
      totalAmount: 0
    })
  }

  //  删除购物车
  onDelCart() {
    const { cartList, checkList } = this.state
    if (checkList.length <= 0) {
      Taro.showToast({ title: '请选择商品', icon: 'none' })
      return
    }
    Taro.showLoading({title: '请稍后', mask: true})
    const ids = []
    lodash.remove(cartList, function (i, k) {
      const bool = checkList.indexOf(k) >= 0
      if (bool) {
        // @ts-ignore
        ids.push(i.id)
      }
      return bool
    })
    delBatchCart({ ids }).then(() => {
      this.setState({
        cartList,
        checkList: [],
        totalAmount: 0
      }, () => {
        Taro.hideLoading()
      })
      this.setCartCount(cartList.length)
    })
  }

  //  显示选择商品
  setShowSelect(bool) {
    this.setState({
      showSelect: bool
    })
  }

  //  选择sku
  onSelectSku(i, k) {
    Taro.showLoading({title: '请稍后', mask: true})
    skuById(i.productId).then(res => {
      const { data } = res
      // console.log(data)
      data.key = k
      data.skuId = i.skuId
      data.cartId = i.id
      data.number = i.number
      data.specSnap = i.specSnap.split(',')
      data.timestamp = Number(new Date())
      this.setState({
        goodsInfo: data,
        showSelect: true,
      }, () => {
        Taro.hideLoading()
      })
    })
  }

  //  确认选择 sku
  onConfirmSelect(info, number) {
    const { goodsInfo, cartList } = this.state
    Taro.showLoading({title: '请稍后', mask: true})
    updateCart({ id: goodsInfo.cartId, productId: info.productId, skuId: info.skuId, number }).then(() => {
      getCartInfo(goodsInfo.cartId).then(res => {
        cartList[goodsInfo.key] = filterCartInfo(res.data)
        this.setState({
          cartList,
          showSelect: false,
        }, () => {
          this.calcShoppingCart()
          Taro.hideLoading()
        })
      })
    })
  }

  render() {
    const { loading, isLogin, cartList, checkList, goodsInfo, goodsList, totalAmount, cartStatus, showSelect } = this.state
    const disabled = !isSubmit({ checkList })
    return (<View className='page d-f f-d-c'>
      {loading && <Loading/>}
      <View className='cart-scroll'>
        {!isLogin && <View className='cart-status f-g-5 f-d-c'>
          <View className='head-title'>未登录</View>
          <View className='head-desc'>查看不了购物车数据</View>
          <View className='head-btn f-g-5' hoverClass='hover-class--btn' onClick={() => toUserLoginPage()}>去登录</View>
        </View>}
        {isLogin && !cartList.length && <View className='cart-status f-g-5 f-d-c'>
          <View className='head-title'>购物车空空如也</View>
          <View className='head-desc'>赶紧挑点宝贝</View>
          <View className='head-btn f-g-5' hoverClass='hover-class--btn' onClick={() => toHomePage()}>去逛逛</View>
        </View>}
        <View className='cart-body'>
          <View className='cart-list'>
            {!!cartList.length && <View className='cart-operate d-f a-i-c j-c-b'>
              <View className='total-num'>共{cartList.length}件商品</View>
              {cartStatus && <View className='total-num' onClick={this.onSwitchStatus.bind(this, false)}>管理</View>}
              {!cartStatus && <View className='total-num' onClick={this.onSwitchStatus.bind(this, true)}>完成</View>}
            </View>}
            {cartList.map((item, key) => {
              return (<View key={item.id} className='goods-item d-f a-i-s'>
                <View className='goods-checkbox d-f a-s-c' onClick={this.onCheckGoods.bind(this, item, key)}>
                  {checkList.indexOf(key) === -1 && <View className='unchecked-icon'/>}
                  {checkList.indexOf(key) >= 0 && <View className='bnn-icon unchecked-icon check-icon'>&#xe645;</View>}
                </View>
                <Image src={getThumbnailConfig(headImg(item.images), 500, 500, 'fill')} className='goods-img' onClick={() => toGoodsPage({ id: item.productId })}/>
                <View className='other-info d-f f-d-c j-c-b'>
                  <View className='info-header'>
                    <View className='goods-name t-o-e-2'>{item.name}</View>
                    {!!item.isSku && <View className='goods-attr d-f a-i-c j-c-b' onClick={this.onSelectSku.bind(this, item, key)}>
                      <View className='attr-text t-o-e'>{item.specSnap}</View>
                      <View className='bnn-icon attr-icon'>&#xe661;</View>
                    </View>}
                  </View>
                  <View className='info-footer d-f j-c-b a-i-f-e'>
                    <View className='goods-price d-f f-d-c'>
                      <View className='sale-price bnn-number'>
                        <Text className='price-unit'>￥</Text>{formatAmount(item.salePrice, '')}
                      </View>
                    </View>
                    <GoodsNumber min={1} max={99} value={item.number} onChange={this.onChangeNumber.bind(this, item, key)}/>
                  </View>
                </View>
              </View>)
            })}
          </View>
          {!!goodsList.length && <View className='hot-goods'>
            <TitleOne>为您推荐</TitleOne>
            <GoodsOneList>
              {goodsList.map(item => {
                return (<GoodsOneItem key={item.id} info={item}/>)
              })}
            </GoodsOneList>
          </View>}
        </View>
      </View>

      {!!cartList.length && <View className='cart-foot-height'/>}
      {!!cartList.length && <View className='cart-foot' style={{bottom: `${APP_SYSTEM_INFO.tabBarHeight}px`}}>
        <View className='footer-box d-f a-i-s'>
          <View className='check-all d-f a-s-c a-i-c' onClick={this.onCheckAll.bind(this)}>
            {cartList.length === checkList.length ? (<View className='bnn-icon unchecked-icon check-icon'>&#xe645;</View>) : (<View className='unchecked-icon'/>)}
            {/*{cartList.length !== checkList.length && <View className='unchecked-icon'/>}*/}
            {/*{checkList.length && cartList.length === checkList.length && <View className='bnn-icon unchecked-icon check-icon'>&#xe645;</View>}*/}
            <View className='check-all-text m-l-10 l-h-1'>全选</View>
          </View>
          <View className='total-amount d-f a-s-c a-i-c j-c-e'>
            {cartStatus && <View className='bnn-number'>合计：<Text className='amount-num'>￥{totalAmount}</Text></View>}
          </View>
          {cartStatus && <Button disabled={disabled} className='submit-btn d-f a-i-c j-c-c' hoverClass='hover-class--btn' onClick={this.onSubmitCart.bind(this)}>去结算</Button>}
          {!cartStatus && <Button className='delete-btn d-f a-i-c j-c-c' hoverClass='hover-class--btn' onClick={this.onDelCart.bind(this)}>删除</Button>}
        </View>
      </View>}
      {/*<ActionSheetGoods*/}
      {/*  info={goodsInfo}*/}
      {/*  isOpened={showSelect}*/}
      {/*  onClose={this.setShowSelect.bind(this, false)}*/}
      {/*  onConfirm={this.onConfirmSelect.bind(this)}*/}
      {/*/>*/}
      <GoodsSelect goods={goodsInfo} isOpened={showSelect} onClose={this.setShowSelect.bind(this, false)} onConfirm={this.onConfirmSelect.bind(this)}/>
      <View style={{height: `${APP_SYSTEM_INFO.tabBarHeight}px`}}/>
      <TabBar />
    </View>)
  }
}
